package com.codemart.lanze.modules.admin;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codemart.lanze.common.annotation.OperationLog;
import com.codemart.lanze.common.base.controller.AdminBaseController;
import com.codemart.lanze.common.security.token.FormToken;
import com.codemart.lanze.common.validator.group.Create;
import com.codemart.lanze.common.validator.group.Update;
import com.codemart.lanze.modules.cms.entity.Category;
import com.codemart.lanze.modules.cms.entity.Product;
import com.codemart.lanze.modules.cms.service.ICategoryService;
import com.codemart.lanze.modules.cms.service.IProductService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 产品
 * @Author: lanze
 * @Date: 2019-09-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "产品")
@Controller
@RequestMapping("/admin/product")
public class ProductController extends AdminBaseController {

	@Autowired
	private IProductService productService;

	@Autowired
	private ICategoryService categoryService;

	private static final String BASE_PATH = "admin/product/";

	@Value("${imageUrl}")
	public String IMAGE_URL;

	/**
	 * 分页查询产品列表
	 *
	 * @param pageNum
	 *            当前页码
	 * @param name
	 *            产品-查询关键字
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param modelMap
	 * @return
	 */
	@RequiresPermissions("product:list")
	@GetMapping
	public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Long categoryId,
			String searchKey, String startTime, String endTime, ModelMap modelMap) throws Exception {
		try {
			log.debug("分页查询产品列表参数! pageNum = {}, categoryId = {},  searchKey = {},  startTime = {}, endTime = {}",
					pageNum, categoryId, searchKey, startTime, endTime);

			QueryWrapper<Product> ew = new QueryWrapper<>();
			ew.eq("category_id", categoryId);

			IPage<Product> iPage = productService.page(new Page<>(pageNum, PAGESIZE), ew);

			log.info("分页查询产品列表结果！ pageInfo = {}", iPage);

			Category category = new Category();
			if (null != categoryId) {
				category = categoryService.getById(categoryId);
			}

			System.out.println("categoryId==" + categoryId);
			modelMap.put("category", category);

			modelMap.put("pageInfo", iPage);
			modelMap.put("name", searchKey);
			modelMap.put("startTime", startTime);
			modelMap.put("endTime", endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BASE_PATH + "product-list";
	}

	/**
	 * 根据主键ID删除产品
	 *
	 * @param id
	 * @return
	 */
	@OperationLog(value = "删除产品")
	@RequiresPermissions("product:delete")
	@DeleteMapping(value = "/product/{id}")
	public ResponseEntity<String> delete(@PathVariable("id") Long id) {
		log.debug("删除产品! id = {}", id);

		Product product = productService.getById(id);
		if (null == product) {
			log.info("删除的产品不存在! id = {}", id);
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("产品不存在!");
		}

		productService.removeById(id);
		log.info("删除产品成功! id = {}", id);
		return ResponseEntity.ok("已删除!");
	}

	/**
	 * 跳转到产品添加页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("product:create")
	@GetMapping(value = "/add")
	public String add(Long categoryId, ModelMap modelMap) {

		Category category = new Category();
		if (null != categoryId) {
			category = categoryService.getById(categoryId);
		} else {
			category.setId(categoryId);
		}
		modelMap.put("category", category);

		return BASE_PATH + "product-add";
	}

	/**
	 * 添加产品
	 *
	 * @param product
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "添加产品")
	@RequiresPermissions("product:create")
	@ResponseBody
	@PostMapping
	public ModelMap saveAdvertPosition(@Validated({ Create.class }) Product product) {
		ModelMap messagesMap = new ModelMap();

		log.debug("添加产品参数! product = {}", product);

		// 执行保存
		productService.save(product);
		log.info("添加产品成功! productId = {}", product.getId());
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "添加成功!");
		return messagesMap;
	}

	/**
	 * 跳转到产品编辑页面
	 *
	 * @return
	 */
	@FormToken(save = true)
	@RequiresPermissions("product:update")
	@GetMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap modelMap) throws Exception {
		log.debug("跳转到编辑产品信息页面参数! id = {}", id);
		Product product = productService.getById(id);

		Category category = new Category();
		if (null != product) {
			category = categoryService.getById(product.getCategoryId());
		}
		modelMap.put("category", category);

		log.info("跳转到编辑产品信息页面成功!, id = {}", id);
		modelMap.put("product", product);
		modelMap.put("model", product);
		modelMap.put("imageUrl", IMAGE_URL);
		return BASE_PATH + "product-edit";
	}

	/**
	 * 更新产品信息
	 *
	 * @param id
	 * @param product
	 * @return
	 */
	@FormToken(remove = true)
	@OperationLog(value = "编辑产品")
	@RequiresPermissions("product:update")
	@ResponseBody
	@PutMapping(value = "/{productId}")
	public ModelMap updateAdvertPosition(@PathVariable("productId") Long productId,
			@Validated({ Update.class }) Product product) {
		ModelMap messagesMap = new ModelMap();

		log.debug("编辑产品参数! productId= {}, product = {}", productId, product);

		product.setId(productId);
		productService.saveOrUpdate(product);
		log.info("编辑产品成功! productId= {}, product = {}", productId, product);
		messagesMap.put("status", SUCCESS);
		messagesMap.put("message", "编辑成功!");
		return messagesMap;
	}

	/**
	 * 检验产品名是否存在
	 *
	 * @param id
	 * @param name
	 * @return
	 */
	@ResponseBody
	@GetMapping(value = "/isExist")
	public Boolean isExist(Long id, String name) {
		boolean flag = true;
		log.debug("检验产品名称是否存在参数! id= {}, name= {}", id, name);

		Product record = productService.findByName(name);
		if (null != record && !record.getId().equals(id)) {
			flag = false;
		}
		log.info("检验产品名称是否存在结果! flag = {}", flag);
		return flag;
	}

}
